const express = require('express');
const app = express();
const port = 3000;
const DB = require('./db');

// 用于解析application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// 用于解析application/json
app.use(express.json());

// 服务静态文件
app.use(express.static('public'));

// 定义GET路由，响应根路径请求
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html'); // 确保index.html在public文件夹内
});

// 定义POST路由，处理表单提交
app.post('/submit', (req, res) => {
    DB.connect((db) => {
        const collection = db.collection('data');
        collection.insertOne({ input: req.body.inputField }, (err, result) => {
            if (err) throw err;
            console.log('文档插入成功');
            res.send('数据已保存到数据库');
        });
    });
});

app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});